package spider

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

var (
	userAgent  = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
	HttpClient *Client
)

type Client struct {
	http.Client
}

func (client *Client) GetStr(url string) string {
	html, ok := client.Get(url)
	if ok {
		htmlBytes, err := ioutil.ReadAll(html)
		if err != nil {
			fmt.Println("GetStr error", err)
			return ""
		}
		return string(htmlBytes)
	}
	return ""
}

func (client *Client) Get(url string) (io.Reader, bool) {
	if url == "" {
		return nil, false
	}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("=======GET ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET ERROR========")
		return nil, false
	}

	req.Header.Set("User-Agent", userAgent)

	resp, err := client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		fmt.Println("=======GET REQUEST ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET REQUEST ERROR========")
		return nil, false
	}

	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Println("=======GET ReadAll ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET ReadAll ERROR========")
		return nil, false
	}

	return bytes.NewReader(body), true
}

func (client *Client) Post(url string) (io.Reader, bool) {
	if url == "" {
		return nil, false
	}
	req, err := http.NewRequest("Post", url, nil)
	if err != nil {
		fmt.Println("=======GET ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET ERROR========")
		return nil, false
	}

	req.Header.Set("User-Agent", userAgent)

	resp, err := client.Do(req)
	defer resp.Body.Close()
	if err != nil {
		fmt.Println("=======GET REQUEST ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET REQUEST ERROR========")
		return nil, false
	}

	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		fmt.Println("=======GET ReadAll ERROR========")
		fmt.Println(err)
		fmt.Println("=======GET ReadAll ERROR========")
		return nil, false
	}

	return bytes.NewReader(body), true
}

// 初始化 httpClient
func createHTTPClient() *Client {
	return &Client{}
}

func init() {
	fmt.Println("初始化 http client")
	HttpClient = createHTTPClient()
}
